package CleverBotWatcher;
use strict;
use LWP::UserAgent;
use Data::Dumper;

    

sub new{
 my $cl = shift;
 my $self = {
    conf_file => 'CleverBotWatcher.conf',
    ua => LWP::UserAgent->new(),
 };
 return bless $self;
}

sub error{
   my $self = shift; 
   open ERR, ">>err.txt";
   print ERR "$self->{error}.\n";
   close ERR;
   return $self->{error}.""; 
}

sub msg{ 
   return shift->{msg}."";
}

sub load_conf{
 my $self = shift;
 $self->{error}="$self->{conf_file} not found.".__FILE__." line: ".__LINE__, return 0 if !-e $self->{conf_file};
 open CONF, $self->{conf_file} or $self->{error} = "Can't open file $self->{conf_file}: $!".__FILE__." line: ".__LINE__, return 0;
 my @lines = <CONF>;
 my $lines = join '',@lines;
 close CONF;
 $@ = '';
 eval $lines; # in eval will set $self->{conf} and $self->{free_console}
 $self->{error} = "Error while eval: $@".__FILE__." line: ".__LINE__, return 0 if $@;
 $self->{error} = "Eval return empty".__FILE__." line: ".__LINE__, return 0 if !$self->{conf};
 $self->{error} = "Eval return non hashref".__FILE__." line: ".__LINE__, return 0 if ref $self->{conf} ne "HASH";
 
 for my $key ( keys %{ $self->{conf} } ){
    my $hr = $self->{conf}{$key};
    $self->{error} = "icon_name!".Dumper($hr).__FILE__." line: ".__LINE__, return 0 if !$hr->{icon_name};
    $self->{error} = "icon_name not found! ($hr->{icon_name})".Dumper($hr).__FILE__." line: ".__LINE__, return 0 if !-e $hr->{icon_name};
    next if $key == 1;
    $self->{error} = "query!".Dumper($hr).__FILE__." line: ".__LINE__, return 0 if !$hr->{query};
    $self->{error} = "cmd or open!".Dumper($hr).__FILE__." line: ".__LINE__, return 0 if !$hr->{cmd} and !$hr->{open};
 }
 
 return $self->{conf};
}

#-----------------------------------------
sub free_console{ return shift->{free_console} }; # $self->{free_console} was setup in eval , see conf file.
#------------------------------------------------

sub start{
 my $self = shift;
 my %pars = @_;
 @pars{qw/debug timer window/};
 my $rv; # most return index
 for my $key ( sort {$a<=>$b} keys %{ $self->{conf} } ){
    next if $key == 1;
    my $hr = $self->{conf}{$key};
    print Dumper $hr if $pars{debug};
    my $req = HTTP::Request->new( GET => $hr->{query} ) or $self->{error} = "Can't create req ".__FILE__." line: ".__LINE__, return 0;
#    my $req = HTTP::Request->new( GET => "http://127.0.0.1/cgi-bin/clever_bot.cgi?nr=1" ) or $self->{error} = "Can't create req ".__FILE__." line: ".__LINE__, return 0;
    # my $req = HTTP::Request->new(POST => 'http://search.cpan.org/search');
    # $req->content_type('application/x-www-form-urlencoded');
    # $req->content('query=libwww-perl&mode=dist');
          
    my $res = $self->{ua}->request( $req );
    if ($res->is_success) {
         print "content=".$res->content."\n" if $pars{debug};
         my $pairs = $self->read_content( content=>$res->content , %pars ) or $self->{error} = "Can't read content ".__FILE__." line: ".__LINE__.$res->content, return 0;
         print "read_content return: ".Dumper($pairs) if $pars{debug};
         if ( $pairs->{count} ){
            print "WILL RETURN KEY=$key\n" if $pars{debug};
            return $key;# # возвращаем тот ключ по запросу которого получено ненулевое count
         }else{
            print  "DO NOT RETURN KEY=$key, count=0\n" if $pars{debug};
         }    
    }
    else {
         print "status_line=".$res->status_line."\n" if $pars{debug};
         $self->{error} = $self->{msg} = 
         	$res->status_line." ".__FILE__." line: ".__LINE__;
         return 1;
    }    
 }
}

sub read_content{
 my $self = shift;
 my %pars = @_;
 my $content = $pars{content} or $self->{error} = "content is empty!".__FILE__." line: ".__LINE__, return 0;
 print "Called read_content...\n" if $pars{debug};
 my ($csv) = $content =~ /BEGIN(.*)END/is or $self->{error} = "data block is empty!".__FILE__." line: ".__LINE__, return 0;
 $csv =~s/(\<CSV\>)|(\<\/CSV\>)//gi;
 print "csv=$csv\n" if $pars{debug};
 my @pairs = split /\;/, $csv;
 print Dumper \@pairs if $pars{debug};
 $self->{msg} = Dumper \@pairs;
 my %pairs;
 for ( @pairs ){
    my ($k,$v) = split /\=/, $_;
    $pairs{$k} = $v;
 }
 print Dumper \%pairs if $pars{debug};
 return \%pairs;
}

1;
